package com.lap.permission.component;

import com.lap.framework.tools.Uid;
import com.lap.permission.config.SecurityProperties;
import com.lap.permission.domain.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class JwtTokenHelper {
    public static final String USER_ID = "id";

    private final SecurityProperties properties;

    public String createJwt(User user) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, properties.getTimes());

        return Jwts.builder().id(Uid.getId())
                .issuer(properties.getIssuer())//签发人
                .claims(Map.of(USER_ID, user.getId()))
                .issuedAt(new Date())//签发时间
                .expiration(calendar.getTime())//过期时间
                .signWith(getSignInKey())
                .compact();
    }

    public Integer validateJwt(String token) {
        try {
            Claims claims = Jwts.parser()
                    .verifyWith(getSignInKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();

            return claims.get(USER_ID, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }

    private SecretKey getSignInKey() {
        byte[] keyBytes = Decoders.BASE64.decode(properties.getKey());
        return Keys.hmacShaKeyFor(keyBytes);
    }

}
